package com.shopping.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import com.shopping.bean.Goods;
import com.shopping.bean.ShopCar;
import com.shopping.dao.ShopCarDao;
import com.shopping.util.DBUtil;

public class ShopCarDaoImpl implements ShopCarDao {

	JdbcTemplate jt = new JdbcTemplate(DBUtil.getDataSource());
	
	@Override
	public Goods selectGoodsByGoodsId(int goodsId) {
		String sql = "SELECT * FROM goods g,shopcar s WHERE g.goodsId = s.goodsId AND g.goodsId = ?";
		List<Goods> list = jt.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class),goodsId);
		if(list.size() == 0) {
			return null;
		}else {
			return list.get(0);
		}
	}

	@Override
	public int selectUserNum(int userId) {
		String sql = "SELECT count(1) FROM shopcar WHERE userId = ?";
		return jt.queryForObject(sql, Integer.class,userId);
	}

	@Override
	public Map<String, Object> selectByName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Map<String, Object>> selectAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Goods> selectGoodsId(int userId) {
		String sql = "SELECT g.* FROM goods g,shopcar s WHERE g.goodsId = s.goodsId AND s.userId = ?";
		return jt.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class),userId);
	}

	@Override
	public int delGoods(Map<String, String[]> condition) {
		String sql = "delete from shopCar where goodsId = ? and userId = ?";
		int result = 0;
		Set<Entry<String,String[]>> set = condition.entrySet();
		for(Entry<String,String[]> s:set) {
			for(int i = 0; i < s.getValue().length;i++) {
				
				String[] id = condition.get("userId");
				
				int ids = Integer.parseInt(id[0]);
				
				result = jt.update(sql,s.getValue()[i],ids);
				
				if(result == 0) {
					return 0;
				}
			}
		}
		return result;
	}

	@Override
	public List<ShopCar> selectShopCar(int userId) {
		String sql = "SELECT * FROM shopcar WHERE userId = ?";
		return jt.query(sql, new BeanPropertyRowMapper<ShopCar>(ShopCar.class),userId);
	}

	@Override
	public int deleteGoods(int userId, int goodsId) {
		String sql = "DELETE FROM shopcar WHERE goodsId = ? AND userId = ?";
		return jt.update(sql,goodsId,userId);
	}

	@Override
	public ShopCar selectShopCarGoods(int goodsId,int userId) {
		String sql = "SELECT * FROM shopcar WHERE goodsId = ? AND userId = ?";
		List<ShopCar> list = jt.query(sql, new BeanPropertyRowMapper<ShopCar>(ShopCar.class),goodsId,userId);
		if(list.size() == 0) {
			return null;
		}else {
			return list.get(0);
		}
	}	
	
}
